export default class Snake{
    element:HTMLElement;
    head:HTMLElement;
    bodies:HTMLCollection;

    constructor(){

        this.element =document.querySelector('.snake')!;

        this.head = document.querySelector('.snake>div') as HTMLElement;

        this.bodies = this.element.getElementsByTagName('div')
    }

    get X() {
        return this.head.offsetLeft
    }


    get Y() {
        return this.head.offsetTop
    }


    set X(value){
        if(this.X === value){
            return
        }

        if(this.X <0 || this.X >290){
            throw Error("Game Over")
        }

        //屏蔽反向按键：当蛇向右移动，不允许向左按键
         //判断反向： 0是header，1是第二个div，当下一个位置 与 第二个div相同，表示反向了
        if(this.bodies[1] && (this.bodies[1] as HTMLElement).offsetLeft === value ){
            //如果反向，纠正value值，让其继续往下走
            if(this.X > value){//反向 向左
                value = this.X + 10;
            }else{
                value = this.X - 10;
            }
        }

        
        //身体移动
        this.moveBody();

        //设置头位置
        this.head.style.left = value+"px";

        //检查是否撞到
        this.checkHeadBody();
    }

    set Y(value){
        if(this.Y === value){
            return
        }

        if(this.Y <0 || this.Y >290){
            throw Error("Game Over")
        }

        if(this.bodies[1] && (this.bodies[1] as HTMLElement).offsetTop === value ){
            //如果反向，纠正value值，让其继续走
            if(this.Y > value){//反向-向上
                value = this.Y + 10;
            }else{
                value = this.Y - 10;
            }
        }

         //身体移动
         this.moveBody();

         //设置头位置
         this.head.style.top = value+"px";
 
         //检查是否撞到
         this.checkHeadBody();

    }


    addBody(){
        //插入div
        this.element.insertAdjacentHTML('beforeend',"<div></div>");
    }

    moveBody(){
        //移动身体，从后向前，将值覆盖即可
        for(let i = this.bodies.length -1;i>0;i--){
            //从后向前查，将当前位置调整为靠前元素的位置
            (this.bodies[i] as HTMLElement).style.top = (this.bodies[i-1] as HTMLElement).offsetTop+"px";
            (this.bodies[i] as HTMLElement).style.left = (this.bodies[i-1] as HTMLElement).offsetLeft+"px";
        }
    }

    /**
     * 是否撞到自己身体
     */
    private checkHeadBody(){
        for(let i = 1;i<this.bodies.length;i++){
            let el = this.bodies[i] as HTMLElement
            if(el.offsetLeft === this.X &&el.offsetTop === this.Y ){
                throw Error("撞到自己了")
            }
        }
    }
}